package com.sudo.boot.service.sys_my.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.sudo.boot.base.constant.enums.EnumYesNo;
import com.sudo.boot.base.util.IfFail;
import com.sudo.boot.mapper.sys.entity.SysRole;
import com.sudo.boot.mapper.sys.entity.SysUser;
import com.sudo.boot.mapper.sys.entity.SysUserRole;
import com.sudo.boot.mapper.sys.mapper.SysRoleMapper;
import com.sudo.boot.mapper.sys.mapper.SysUserMapper;
import com.sudo.boot.mapper.sys.mapper.SysUserRoleMapper;
import com.sudo.boot.mapper.sys.model.bo.my.MyUserBoEdit;
import com.sudo.boot.mapper.sys.model.bo.my.MyUserBoPassword;
import com.sudo.boot.mapper.sys.model.vo.my.MyUserInfoVo;
import com.sudo.boot.satoken.util.BootStpUtil;
import com.sudo.boot.service.sys_my.MyUserService;
import com.sudo.boot.service.sys_my.converter.MyUserConverter;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import static com.sudo.boot.mapper.sys.entity.table.SysRoleTableDef.SYS_ROLE;
import static com.sudo.boot.mapper.sys.entity.table.SysUserRoleTableDef.SYS_USER_ROLE;
import static com.sudo.boot.mapper.sys.entity.table.SysUserTableDef.SYS_USER;

/**
 * 我的用户信息
 *
 * @author DayDayUp
 * @datetime 2023-11-09 16:43
 **/
@Service
public class MyUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements MyUserService {
    @Resource
    private MyUserConverter myUserConverter;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public void edit(MyUserBoEdit bo) {
        // 编辑用户
        Integer currUserId = BootStpUtil.getCurrUserId();
        String currUsername = BootStpUtil.getCurrUsername();
        SysUser sysUser = myUserConverter.toSysUser(bo);
        sysUser.setId(currUserId);
        IfFail.dealInt(() -> mapper.update(sysUser));

        // 取消默认角色
        SysUserRole cancelUserRole = new SysUserRole();
        cancelUserRole.setDefaultRole(EnumYesNo.NO.getCode());
        QueryWrapper cancelQuery = QueryWrapper.create()
                .where(SYS_USER_ROLE.DEFAULT_ROLE.eq(EnumYesNo.YES.getCode()))
                .and(SYS_USER_ROLE.USERNAME.eq(currUsername));
        IfFail.dealInt(() -> sysUserRoleMapper.updateByQuery(cancelUserRole, cancelQuery));

        // 设置默认角色（如果角色不存在也会抛出异常）
        SysUserRole setUserRole = new SysUserRole();
        setUserRole.setDefaultRole(EnumYesNo.YES.getCode());
        QueryWrapper setQuery = QueryWrapper.create()
                .where(SYS_USER_ROLE.ROLE_CODE.eq(bo.getDefaultRoleCode()))
                .and(SYS_USER_ROLE.USERNAME.eq(currUsername));
        IfFail.dealInt(() -> sysUserRoleMapper.updateByQuery(setUserRole, setQuery));
    }

    @Override
    public void resetPassword(MyUserBoPassword bo) {
        Integer currUserId = BootStpUtil.getCurrUserId();
        // 判断用户新密码与确认密码是否一致
        Assert.isTrue(bo.getNewPassword().equals(bo.getConfirmPassword()),"新密码与确认密码不一致");

        // 判断旧密码是否正确
        SysUser sysUser = mapper.selectOneById(currUserId);
        String oldPwdDecrypt = BootStpUtil.encryptPwd(bo.getOldPassword());
        Assert.isTrue(oldPwdDecrypt.equals(sysUser.getPassword()),"旧密码不正确");

        // 重置新密码
        SysUser newUser = new SysUser();
        newUser.setId(currUserId);
        newUser.setPassword(BootStpUtil.encryptPwd(bo.getNewPassword()));
        IfFail.dealInt(() -> mapper.update(newUser));
    }

    @Override
    public MyUserInfoVo getMyUserInfo() {
        MyUserInfoVo userInfoVo = new MyUserInfoVo();

        String currUsername = BootStpUtil.getCurrUsername();
        SysUser sysUser = mapper.selectOneByCondition(SYS_USER.USERNAME.eq(currUsername));
        userInfoVo.setUserId(sysUser.getId());
        userInfoVo.setUsername(sysUser.getUsername());
        userInfoVo.setNickName(sysUser.getNickName());

        String currRole = BootStpUtil.getCurrRole();
        SysRole sysRole = sysRoleMapper.selectOneByCondition(SYS_ROLE.ROLE_CODE.eq(currRole));
        userInfoVo.setRoleId(sysRole.getId());
        userInfoVo.setRoleCode(sysRole.getRoleCode());
        userInfoVo.setRoleName(sysRole.getRoleName());

        return userInfoVo;
    }
}
